<?php
/**
 * Created by PhpStorm.
 * User: zhaoyi
 * Date: 2022/1/26
 * Time: 11:46.
 */

declare(strict_types=1);

namespace App\Application\Api\Controller;

use App\Annotation\Api;
use App\Application\Admin\Model\Coupon;
use App\Application\Admin\Model\Room;
use App\Application\Admin\Service\AdminSettingService;
use App\Application\Admin\Service\CityService;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\PostMapping;
use Hyperf\HttpServer\Annotation\GetMapping;
use Hyperf\HttpServer\Annotation\Controller;

use App\Application\Admin\Model\Meituan;

#[Controller("/api/meituan/")]
class MeituanController extends AbstractController
{
    #[Inject]
    protected AdminSettingService $setting;

//更新token
    #[Api]
    #[getMapping("refresh_token")]
    function refresh_token()
    {
        $list = Meituan::where('refresh_token', '<>', '')->select('*')
            ->get()->toArray();
        foreach ($list as $key => $val) {
            if ($val['access_token'] !== "") {
                //还剩2天过期
                if ($val['expire_in'] - 2 * 86400 < time()) {
                    $developerId = 112999;
                    $timestamp = (string)time();
                    $charset = 'UTF-8';
                    $data = ["timestamp" => $timestamp, "scope" => "all", "refreshToken" => $val['refresh_token'], "grantType" => "refresh_token", "developerId" => $developerId,
                        "charset" => $charset, "businessId" => 58];
                    $sign = self::get_sign("gfrwhysgtwklutho", $data);
                    $params = ["timestamp" => $timestamp, "scope" => "all", "refreshToken" => $val['refresh_token'], "grantType" => "refresh_token", "developerId" => $developerId,
                        "charset" => $charset, "businessId" => 58, "sign" => $sign];
                    $url = "https://api-open-cater.meituan.com/oauth/refresh";
                    $header = array(
                        'Content-Type:' . 'application/x-www-form-urlencoded; charset=UTF-8'
                    );
                    $data = $this->meituan_curl_post($url, $params, $header);
                    $return = json_decode($data, true);
                    //记录日志 勿删
                    if ($return['code'] == 0) {
                        $update = array();
                        $update['access_token'] = $return['data']['accessToken'];
                        $update['expire_in'] = $return['data']['expireIn'];
                        $update['opBizCode'] = $return['data']['opBizCode'];
                        $update['opBizname'] = $return['data']['opBizName'];
                        $update['refresh_token'] = $return['data']['refreshToken'];
                        $update['scope'] = $return['data']['scope'];
                        Meituan::where(['store_id' => $val['store_id']])->update($update);
                    }
                }
            }
        }
    }

    #[Api]
    #[PostMapping("index")]
    function index()
    {
        $user = $this->checkToken();
        $receipt_code = trim($this->request->input('receipt_code', ''));
        $store_id = trim($this->request->input('store_id', ''));
        // 查询门店
        $store = Meituan::where('store_id', $store_id)->select('*')
            ->first() ?: [];
        if (empty($store)) {
            return $this->returnErrorJson('当前门店未配置美团验券信息,请切换门店后验券');
        }
        if ($store->access_token) {
            $developerId = 112999;
            $businessId = 58;
            $timestamp = time();
            $charset = 'utf-8';
            $biz1 = ["receiptCode" => $receipt_code];
            $data1 = ["appAuthToken" => $store->access_token, "timestamp" => $timestamp, "charset" => $charset, "developerId" => $developerId,
                "version" => 2, "businessId" => $businessId, 'biz' => json_encode($biz1)];
            $sign1 = self::get_sign("gfrwhysgtwklutho", $data1);
            $params1 = ["appAuthToken" => $store->access_token, "timestamp" => $timestamp, "charset" => $charset, "developerId" => $developerId,
                "version" => 2, "businessId" => $businessId, 'biz' => json_encode($biz1), "sign" => $sign1];
            $url1 = "https://api-open-cater.meituan.com/ddzh/tuangou/receipt/prepare";
            $header = array(
                'Content-Type:' . 'application/x-www-form-urlencoded; charset=UTF-8'
            );
            $data = self::meituan_curl_post($url1, $params1, $header);
            $return1 = json_decode($data, true);
            if ($return1['code'] == 'OP_SUCCESS' || 1) {
                //    $card_where['meituan_id'] = $return1['data']['dealGroupId'];
                $card_where['meituan_id'] = 944118486;
                $card_list = Coupon::where($card_where)->select('*')
                    ->first() ?: [];;
                if (empty($card_list)) {
                    return $this->returnErrorJson('未配置美团验券信息,或切换卷类型试试');
                }
                $biz = ["receiptCode" => $receipt_code, "count" => 1, "requestId" => $receipt_code, "appShopAccountName" => $store->app_shop_accountname, "appShopAccount" => $store->app_shop_account];
                $data = ["appAuthToken" => $store->access_token, "timestamp" => $timestamp, "charset" => $charset, "developerId" => $developerId,
                    "version" => 2, "businessId" => $businessId, 'biz' => json_encode($biz)];
                $sign = self::get_sign("gfrwhysgtwklutho", $data);
                $params = ["appAuthToken" => $store->access_token, "timestamp" => $timestamp, "charset" => $charset, "developerId" => $developerId,
                    "version" => 2, "businessId" => $businessId, 'biz' => json_encode($biz), "sign" => $sign];
                $url = "https://api-open-cater.meituan.com/ddzh/tuangou/receipt/consume";
                $data = $this->meituan_curl_post($url, $params, $header);
                $return = json_decode($data, true);
                if ($return['code'] == 'OP_SUCCESS' || 1) {
                    //团购
                    if (isset($return['data']['result'][0]['dealGroupId'])) {
                        if (isset($return['data']['result'][0]['dealGroupId'])) {
                            $dealgroup_id = trim($return['data']['result'][0]['dealGroupId']);
                        }   //美团商品id
                        $card_where['meituan_id'] = $dealgroup_id;

                        $card_list = Coupon::where($card_where)->select('*')
                            ->first() ?: [];;
                    }
                    $card_where['meituan_id'] = 944118486;
                    $card_list = Coupon::where($card_where)->select('*')
                        ->first() ?: [];;
                    $dataCoupon = array(
                        'coupon_id' => $card_list->coupon_id,
                        'name' => $card_list->name,
                        'condition' => $card_list->condition,
                        'roomids' => json_encode($card_list->roomids),
                        'time' => $card_list->time,
                        'hours_add_time' => $card_list->hours_add_time,
                        'hours_end_time' => $card_list->hours_end_time,
                        'member_id' => $user->member_id,
                        'store_id' => $store_id,
                        'type' => $card_list->type,
                        'money' => $card_list->money,
                        'price' => $card_list->price,
                        'end_time' => $card_list->end_time,
                    );
                    if (Db::table('coupon_member')->insert($dataCoupon)) {
                        // 更新领取数量
                        $coi = array(
                            'num' => $card_list['num'] - 1,
                        );
                        $rescoupon = Coupon::where('coupon_id', $card_list->coupon_id)->update($coi);
                        return $this->returnSuccessJson(compact('rescoupon'));
                    }
                } else {
                    return $this->returnErrorJson($return['msg']);
                }
            } else {
                return $this->returnErrorJson($return1['msg']);
            }
        } else {
            return $this->returnErrorJson('获取access_token配置信息失败');
        }
    }
}